package com.framework.utils.httpClient;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;

/**
 * 功能描述:
 *
 * @author ck
 * @date 2018/11/29 13:24
 */
public class HttpSessionId {
	public static void main(String[] args) {
		System.out.print(geSessionId("https://mpos.ruiyinxin.com/qtfr/login/login.jsp"));
	}

	/**
	 * 获取网站的sessionId
	 * @param url
	 * @return
	 */
	public static String geSessionId(String url){
		// 需登陆后访问的 Url
		HttpClient httpClient = new HttpClient();
		String sessionId = "";
		// 模拟登陆，按实际服务器端要求选用 Post 或 Get 请求方式
		GetMethod postMethod = new GetMethod(url);

		// 设置登陆时要求的信息，用户名和密码
		try {
			// 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
			httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
			httpClient.executeMethod(postMethod);
			// 获得登陆后的 Cookie
			Cookie[] cookies = httpClient.getState().getCookies();
			sessionId = cookies[0].toString();

		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return sessionId;
	}
}
